import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Navigator, Block, CheckboxGroup, Image} from '@tarojs/components'
import {AtSearchBar, AtIcon} from 'taro-ui'
import {MySellerListItem, PlatformSet} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {MY_SELLER_LIST, LIST_FIRST_SELLER, IDENTITY, MY_SELLER_TATAL, RESOURCE_URL} from '../../constants/api'
import {user} from '../../utils/user.service'
import {platform} from '../../utils/platform-settting.service'
import {newHttp} from "../../utils/request";
import {vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";
import './list.scss'

interface MySellerListItemDiy extends MySellerListItem {
  selected?: boolean
}

export default class List extends Component {
  state: {
    index: number
    searchText: string
    sellerList: MySellerListItemDiy[]
    noItem: boolean
    all: number // 运营中心进入为 1  生意经进入为 0
    tipsNum: number
    sequence: 'asc' | 'desc'
    sortField: string[]
    keyIndex: number
    sortFieldText: any
    seller_tatal: any
    dateFlag: string
  } = {
    searchText: '',
    index: 0,
    sellerList: [],
    noItem: false,
    all: 0,
    tipsNum: 0,
    sequence: 'desc',
    sortField: ['add_date', 'last_login_date', 'new_add_date', 'rebate_range'],
    sortFieldText: {
      add_date: '注册时间',
      last_login_date: '最新来访',
      new_add_date: '最新出单',
      rebate_range: '返利佣金'
    },
    keyIndex: 0,
    dateFlag: '本月',
    seller_tatal: {
      "sum_rebate_fee": 0.00,
      "sum_order_num": 0,
      "sum_total_fee": 0.00
    }
  }
  stage = ['本月', '上月', '全部']
  page = 1
  platformSet: PlatformSet | false = false

  async componentDidMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.platformSet = await platform.getSetting()
    const all = parseInt(Taro.getCurrentInstance().router.params.all) || 0

    Taro.showLoading({title: '加载中...'})
    const sellerList = await this.getData(this.page)
    if (sellerList) {
      if (sellerList.length === 0) {
        this.setState({noItem: true, sellerList, all})
      } else {
        this.setState({sellerList, all})
      }
    } else {
      this.setState({noItem: true, all})
    }
    setTimeout(() => {
      Taro.hideLoading()
    }, 100)
  }

  async componentDidShow() {
    Taro.setNavigationBarTitle({
      title: '我的' + process.env.fxName
    })
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }

    const ret = await newHttp.get(MY_SELLER_TATAL, {})
    let seller_tatal = this.state.seller_tatal
    if (ret && ret.data) {
      seller_tatal = ret.data
    }
    this.setState({seller_tatal})
  }

  searchClick() {
    this.setState({sellerList: []}, async () => {
      this.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  searchChange(value) {
    this.setState({searchText: value})
  }

  clearSearch() {
    this.setState({sellerList: [], searchText: ''}, async () => {
      this.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  typeChange(index) {
    this.setState({index, dateFlag: this.stage[index], sellerList: []}, async () => {
      this.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  async getData(page) {
    const {index, sequence, sortField, keyIndex} = this.state
    const url = Taro.getCurrentInstance().router.params.all === '0' ? MY_SELLER_LIST : LIST_FIRST_SELLER
    const sellerList = await http.get<MySellerListItemDiy[]>(url, {
      pageNumber: page,
      dateFlag: this.stage[index],
      k: this.state.searchText,
      sequence,
      sortField: sortField[keyIndex]
    })
    if (this.platformSet && this.platformSet.platformSellerType === 0) {
      sellerList && sellerList.forEach(item => {
        item.selected = false
      })
    }
    return sellerList
  }

  async secondry(id, name, count) {
    if (this.state.all === 1) {
      if (count > 0) {
        let mpkey = ''
        const uInfo = Taro.getStorageSync('user') || ''
        if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
          mpkey = uInfo.mpkey
        }
        Taro.navigateTo({url: `/distributor/list/children?id=${id}&name=${name}` + '&mpkey=' + mpkey})
      } else {
        Taro.showToast({title: '没有下一级了', icon: 'none'})
      }
    }
  }

  checkChange(res) {
    const sellerList = this.state.sellerList.map(item => {
      item.selected = !!res.detail.value.includes(String(item.id));
      return item
    })
    this.setState({sellerList})
  }

  selectAll() {
    const sellerList = this.state.sellerList.map(item => {
      item.selected = true
      return item
    })
    this.setState({sellerList})
  }

  sequenceChange(index) {
    const {keyIndex, sequence} = this.state
    const that = this
    let newsequence = 'desc'
    if (index == keyIndex) {
      newsequence = sequence == 'asc' ? 'desc' : 'asc'
    }
    that.setState({keyIndex: index, sequence: newsequence}, async () => {
      that.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  showTips(num) {
    const that = this
    that.setState({tipsNum: num}, () => {
      const timer = setTimeout(() => {
        that.setState({
          tipsNum: 0
        })
        clearTimeout(timer)
      }, 2100)
    })
  }

  render() {
    const {
      searchText,
      index,
      sellerList,
      noItem,
      all,
      tipsNum,
      sortField,
      sortFieldText,
      keyIndex,
      sequence,
      seller_tatal,
      dateFlag
    } = this.state
    return (
      <View className='dist-list-root'>
        <GzhAuth />
        <Index />
        <AtSearchBar onClear={this.clearSearch.bind(this)} onActionClick={this.searchClick.bind(this)}
          value={searchText} onChange={this.searchChange.bind(this)}
        ></AtSearchBar>
        <View className='top-info'>
          <View className='top-info-list'>
            <View className='title'>团队总人数<View onClick={this.showTips.bind(this, 1)} className='aticon'> <AtIcon
              value='help' size='13' color='#bfbfbf'
            ></AtIcon></View></View>
            <View className='num'>{seller_tatal.team_count}</View>
            <View className={`tips ${tipsNum == 1 ? 'twos' : ''}`}>发展的{process.env.fxName}总人数</View>
          </View>
          <View className='top-info-list'>
            <View className='title'>团队总销售额<View onClick={this.showTips.bind(this, 2)} className='aticon'> <AtIcon
              value='help' size='13' color='#bfbfbf'
            ></AtIcon></View></View>
            <View className='num'>{seller_tatal.sum_total_fee}</View>
            <View className={`tips ${tipsNum == 2 ? 'twos' : ''}`}>已付款,已完成订单的团队总销售额</View>
          </View>
          <View className='top-info-list'>
            <View className='title'>团队总返利<View onClick={this.showTips.bind(this, 3)} className='aticon'> <AtIcon
              value='help' size='13' color='#bfbfbf'
            ></AtIcon></View></View>
            <View className='num'>{seller_tatal.sum_rebate_fee}</View>
            <View className={`tips ${tipsNum == 3 ? 'twos' : ''}`}>已核验，未核验订单的团队总返利金额</View>
          </View>
          <View className='top-info-list'>
            <View className='title'>团队总订单数 <View onClick={this.showTips.bind(this, 4)} className='aticon'> <AtIcon
              value='help' size='13' color='#bfbfbf'
            ></AtIcon></View></View>
            <View className='num'>{seller_tatal.sum_order_num}</View>
            <View className={`tips tips3 ${tipsNum == 4 ? 'twos' : ''}`}>已付款,已完成的团队总订单数</View>
          </View>
        </View>
        <View className='header'>
          <View className='header-tabs'>
            {this.stage.map((item, i) =>
              <View className={`tabs-list ${i == index ? 'on' : ''}`} key={i}
                onClick={this.typeChange.bind(this, i)}
              >{item}</View>
            )}
          </View>
          <View className='sortField'>
            {sortField.map((item, i) =>
              <View className={`sortField-list ${i == keyIndex ? 'on' : ''}`} key={i}
                onClick={this.sequenceChange.bind(this, i)}
              >{sortFieldText[item]}
                <Image
                  src={i == keyIndex ? 'https://resource.ivcheng.com/resources/images/sequenceIcon.png' : 'https://resource.ivcheng.com/resources/images/sequenceIcon2.png'}
                  className={`sequence ${sequence} ${process.env.TARO_ENV == 'h5' ? 'h5-sequence' : ''}`}
                  mode='widthFix'
                ></Image>
              </View>
            )}
          </View>
        </View>
        {sellerList.length > 0 && <CheckboxGroup onChange={this.checkChange.bind(this)} className='list-box'>
          {sellerList.length > 0 && sellerList.map((item: any) => <View className='list-item' key={item.id}>
            {all === 0 && <Navigator
              url={`/distributor/order/reseller-order?sid=${item.id}&dateFlag=${encodeURIComponent(dateFlag)}`}
            >
              <View className='list-item-top'>
                <Image
                  src={item.user_photo || 'https://resource.ivcheng.com/resources/weapp/images/headimg.png'}
                ></Image>
                <View className='name'>
                  <Text>{item.user_nick_name || item.user_phone || ''}（{item.site_name || ''}）</Text>
                  <Text>最近登录时间：{item.last_login_date || ''}</Text>
                  {item.status === 2 &&
                    <Image className='disabled-img' src={RESOURCE_URL + "/upload/images/20210309/1615282191845_636.png"}
                      mode='widthFix'
                    />}
                </View>
              </View>
              <View className='list-item-bottom'>
                <View>出单量：<Text>{item.off_order || '0'}</Text></View>
                <View>销售额：<Text>{item.self_range || '0'}</Text></View>
                <View>返利：<Text>{item.rebate_range || '0'}</Text></View>
              </View>
            </Navigator>}
            {all === 1 && <Block> <View className='head'>
              <View className='name-box' onClick={this.secondry.bind(this, item.id, item.real_name, item.team_count)}>
                {item.real_name && <Text className='name'>{item.real_name},</Text>}
                <Text className='phone'>{item.phone || ''}</Text>
              </View>
              <Navigator className='order-number'
                url={`/distributor/order/reseller-order?sid=${item.id}&dateFlag=${encodeURIComponent(dateFlag)}`}
              ><AtIcon
                prefixClass='xxhz' value='fenxiaodingdan' size='16'
              ></AtIcon><Text
                decode
              > {item.off_order}单</Text></Navigator>
            </View>
              <View className='all-title'>{this.stage[this.state.index]}</View>
              <View className='all-content'>
                <View className='all-item'>
                  <View className='number'>{item.team_count_range}</View>
                  <View className='label'>发展人数</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_range}</View>
                  <View className='label'>团队销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.self_range}</View>
                  <View className='label'>个人销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_rebate_range}</View>
                  <View className='label'>团队返利</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.rebate_range}</View>
                  <View className='label'>个人返利</View>
                </View>
              </View>
              <View className='all-title total'>总计</View>
              <View className='all-content'>
                <View className='all-item'>
                  <View className='number'>{item.team_count}</View>
                  <View className='label'>总团队人数</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_all}</View>
                  <View className='label'>团队总销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.self_all}</View>
                  <View className='label'>个人总销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_rebate_all}</View>
                  <View className='label'>团队总返利</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.rebate_all}</View>
                  <View className='label'>个人总返利</View>
                </View>
              </View>
            </Block>}
          </View>)}
        </CheckboxGroup>}
        {noItem && <View className='no-item'>
          <View className='tips'><Text decode>您还没有下属{process.env.fxName}&nbsp;</Text><Navigator
            url='/main/my/distributor/index'
            className='link'
          >马上邀请</Navigator></View>
        </View>}
      </View>
    )
  }
}
